package com.ews.onlineexchange.service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.enterprise.inject.Model;
import javax.persistence.EntityGraph;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.ews.onlineexchange.model.Bulletin;
import com.ews.onlineexchange.model.DataEntity;
import com.ews.onlineexchange.model.TradeStatus;

@Model
public class PublicityBulletinList extends EntityQuery<Bulletin> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public PublicityBulletinList() {
		super();
		setOrder( "chooseTime DESC" );
	}

	@Override
	protected List<Predicate> getRestrictions( CriteriaBuilder cb, Root<Bulletin> entity ) {
		List<Predicate> restrictions = super.getRestrictions( cb, entity );
		restrictions.add( cb.equal( entity.get( "delFlag" ), DataEntity.DEL_FLAG_NORMAL ) );
		Calendar now = Calendar.getInstance();
		Calendar oneDayBefore = Calendar.getInstance();
		oneDayBefore.set( Calendar.DAY_OF_MONTH, oneDayBefore.get( Calendar.DAY_OF_MONTH ) - 1 );
		restrictions.add( cb.between( entity.<Date>get( "overTime" ), oneDayBefore.getTime(), now.getTime() ) );
		restrictions.add( cb.equal( entity.get( "tradeStatus" ), TradeStatus.Agreed ) );
		restrictions.add( cb.isFalse( entity.<Boolean>get( "cancelled" ) ) );

		return restrictions;
	}
	
	@Override
	protected void setHint( TypedQuery<Bulletin> query ) {
		EntityGraph<?> entityGraph = entityManager.getEntityGraph( "Bulletin.QualificationGroup" );
		query.setHint( "javax.persistence.loadgraph", entityGraph );		
	}
}
